import { Injectable } from '@nestjs/common';
import { CreateGoodDto } from './dto/create-good.dto';
import { UpdateGoodDto } from './dto/update-good.dto';
import { Goods } from './entities/goods.entity';
import { Category } from 'src/category/entities/category.entity';

@Injectable()
export class GoodsService {
  async create(createGoodDto: CreateGoodDto) {
    let category = await Category.findOneBy({ id: createGoodDto.categoryId });

    return Goods.save({
      ...createGoodDto,
      isShow: true,
      create_time: new Date(),
      update_time: new Date(),
      delete_time: null,
      category: category,
    });
  }

  async findAll(pageNum: number, pageSize: number) {
    const [list, count] = await Goods.findAndCount({
      relations: ['category'],
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
    });

    return { list, count };
  }

  findOne(id: number) {
    return Goods.findOneBy({ id });
  }

  update(id: number, updateGoodDto: UpdateGoodDto) {
    return Goods.update(id, { ...updateGoodDto });
  }

  remove(id: number) {
    return Goods.update(id, { delete_time: new Date() });
  }

  async bindCategory(goodId: number, categoryId: number) {
    let category = await Category.findOneBy({ id: categoryId });
    return Goods.update(goodId, { category });
  }
}
